<template>
  <span v-if="props.showText">{{currName}}</span>
  <el-checkbox-group
    v-else
    v-model="currValue"
    class="cc-checkbox"
    :disabled="inputDisabled"
    @change="handleChange"
  >
    <el-checkbox
      v-for="item in options"
      :key="item.key"
      :value="item.key"
      :disabled="item.disabled === true"
    >{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>

<script setup>
import { ref, watch, inject } from 'vue';
import { useDisabled } from 'element-plus';

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  options: [Array, String],
  allowCreate: {
    type: Boolean,
    default: false
  },
  filterable: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: '--请选择--'
  },
  showText: Boolean
});
const formData = inject('formData');
const currValue = ref([]);
const currName = ref('');
const options = ref([]);
const inputDisabled = useDisabled();

const init = (data) => {
  if (data.options) {
    if (Array.isArray(data.options)) {
      options.value = data.options;
    } else if (typeof data.options === 'string') {
      const optionList = [];
      data.options.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }
  }

  calcValue();
};

const calcValue = () => {
  if (props.showText) {
    const names = [];
    options.value.forEach(option => {
      currValue.value.forEach(value => {
        if (option.key === value) {
          names.push(option.value);
        }
      });
    });
    currName.value = names.join(',');
  }
};

const handleChange = (event) => {
  formData.value[props.prop] = currValue.value.join(',');
  emit('change', event);
};

watch(() => props, (data) => {
  init(data);
}, {immediate: true, deep: 1});

watch(() => formData.value[props.prop], (data) => {
  currValue.value = data ? data.split(',') : [];
  calcValue();
}, {immediate: true});

watch(() => currValue.value, (val) => {
  if (val) {
    formData.value[props.prop] = val.filter(item => item && item !== '').join(',');
  } else {
    formData.value[props.prop] = '';
  }
});
</script>

<style scoped>
.cc-checkbox {
  text-align: left;
}
</style>